package com.way.fileexplorer.activities;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.way.fileexplorer.R;
import com.way.fileexplorer.adapters.CopyDestListAdapter;
import com.way.fileexplorer.adapters.QuickScanCursorAdapter;
import com.way.fileexplorer.util.ActivityUtils;
import com.way.fileexplorer.util.FileSort;
import com.way.fileexplorer.util.FileType;
import com.way.fileexplorer.util.FileUtil;
import com.way.fileexplorer.util.IntentUtil;
import com.way.fileexplorer.util.Slog;
import com.way.fileexplorer.util.StorageUtil;

public class OverViewActivity extends Activity implements OnItemClickListener {
	private final int MENU_MULTISELECT = 0;
	private final int MENU_SORT = 1;
	private final int MENU_INSTALL_ALL = 2;
	public static final int MENU_COPY = 10;
	public static final int MENU_CUT = 11;
	public static final int MENU_DELETE = 12;
	public static final int MENU_SHARE = 13;
	public static final int MENU_RENAME = 14;
	public static final int MENU_DETAIL = 15;
	public static final int MENU_SETAS = 16;
	public static final int MULTI_SELECT = 100;
	private int mFileType;
	private ListView mListView;
	private View mEmptyView;
	private QuickScanCursorAdapter mAdapter;
	private Context mContext;
	private int mSortBy;

	private Handler handler = new Handler();

	// bug 210726 begin
	private BroadcastReceiver mReceiver;

	// bug 210726 end

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_over_view);
		mContext = OverViewActivity.this;
		ActionBar actionbar = getActionBar();
		actionbar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP
				| ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_USE_LOGO
				| ActionBar.DISPLAY_SHOW_TITLE);
		Intent data = getIntent();
		if (null != data) {
			mFileType = data.getIntExtra("fileType", 0);
			mListView = (ListView) findViewById(R.id.overview_file_list);
			mEmptyView = findViewById(R.id.overview_empty_view);
			switch (mFileType) {
			case FileType.FILE_TYPE_AUDIO:
				mAdapter = new QuickScanCursorAdapter(this,
						QuickScanCursorAdapter.RESOURCE_AUDIO, mEmptyView,
						mListView, false);
				actionbar.setTitle(R.string.quickscan_audio);
				actionbar.setLogo(R.drawable.logo_quickscan_audio_ic);
				break;
			case FileType.FILE_TYPE_IMAGE:
				mAdapter = new QuickScanCursorAdapter(this,
						QuickScanCursorAdapter.RESOURCE_IMAGE, mEmptyView,
						mListView, false);
				actionbar.setTitle(R.string.quickscan_image);
				actionbar.setLogo(R.drawable.logo_quickscan_image_ic);
				break;
			case FileType.FILE_TYPE_DOC:
				mAdapter = new QuickScanCursorAdapter(this,
						QuickScanCursorAdapter.RESOURCE_DOC, mEmptyView,
						mListView, false);
				actionbar.setTitle(R.string.quickscan_doc);
				actionbar.setLogo(R.drawable.logo_quickscan_doc_ic);
				break;
			case FileType.FILE_TYPE_PACKAGE:
				mAdapter = new QuickScanCursorAdapter(this,
						QuickScanCursorAdapter.RESOURCE_APK, mEmptyView,
						mListView, false);
				actionbar.setTitle(R.string.quickscan_apk);
				actionbar.setLogo(R.drawable.logo_quickscan_apk_ic);
				break;
			case FileType.FILE_TYPE_VIDEO:
				mAdapter = new QuickScanCursorAdapter(this,
						QuickScanCursorAdapter.RESOURCE_VIDEO, mEmptyView,
						mListView, false);
				actionbar.setTitle(R.string.quickscan_video);
				actionbar.setLogo(R.drawable.logo_quickscan_video_ic);
				break;
			}

			mListView.setAdapter(mAdapter);
			mListView.setOnItemClickListener(this);
			mListView
					.setOnCreateContextMenuListener(mFileListOnCreateContextMenuListener);

			// bug 210726 begin
			IntentFilter filter = new IntentFilter();
			filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
			filter.addAction(Intent.ACTION_MEDIA_EJECT);
			filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
			filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
			filter.addDataScheme("file");
			mReceiver = new StorageReceiver();
			registerReceiver(mReceiver, filter);
			// bug 210726 end
		} else {
			finish();
		}
	}

	// bug 210726 begin
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (null != mReceiver) {
			unregisterReceiver(mReceiver);
		}
	}

	private class StorageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Slog.d("OverView",
					"Receive Broadcast, action=" + intent.getAction());
			if (Intent.ACTION_MEDIA_MOUNTED.equals(intent.getAction())
					|| Intent.ACTION_MEDIA_EJECT.equals(intent.getAction())
					|| Intent.ACTION_MEDIA_BAD_REMOVAL.equals(intent
							.getAction())
					|| Intent.ACTION_MEDIA_UNMOUNTED.equals(intent.getAction())) {
				mAdapter.refresh();
			}
		}
	}

	// bug 210726 end

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		File file = mAdapter.getFileList().get(position);
		Intent intent = IntentUtil.getIntentByFileType(this, mFileType, file);
		if (intent != null) {
			this.startActivity(intent);
		} else {
			Toast.makeText(view.getContext(), R.string.msg_invalid_intent,
					Toast.LENGTH_SHORT).show();
		}
	}

	private final OnCreateContextMenuListener mFileListOnCreateContextMenuListener = new OnCreateContextMenuListener() {
		@Override
		public void onCreateContextMenu(ContextMenu menu, View v,
				ContextMenuInfo menuInfo) {
			AdapterView.AdapterContextMenuInfo info;
			try {
				info = (AdapterView.AdapterContextMenuInfo) menuInfo;
			} catch (ClassCastException e) {
				return;
			}
			final int position = info.position;
			File selectedFile = null;
			Uri selectedFileUri = null;
			FileListMenuClickListener l = null;
			if (mAdapter instanceof QuickScanCursorAdapter) {
				selectedFile = mAdapter.getFileList().get(position);
				selectedFileUri = mAdapter.getFileUri(position);
				l = new FileListMenuClickListener(selectedFile, selectedFileUri);
			}
			menu.setHeaderTitle(R.string.file_option);
			if (selectedFile != null && selectedFile.canRead()
					&& selectedFile.canWrite()) {
				menu.add(0, MENU_COPY, 0, R.string.menu_copy)
						.setOnMenuItemClickListener(l);
				menu.add(0, MENU_CUT, 0, R.string.menu_cut)
						.setOnMenuItemClickListener(l);
				menu.add(0, MENU_DELETE, 0, R.string.operate_delete)
						.setOnMenuItemClickListener(l);
				menu.add(0, MENU_RENAME, 0, R.string.operate_rename)
						.setOnMenuItemClickListener(l);
				menu.add(0, MENU_SHARE, 0, R.string.operate_share)
						.setOnMenuItemClickListener(l);
			}
			if (mFileType == FileType.FILE_TYPE_IMAGE) {
				menu.add(0, MENU_SETAS, 0, R.string.set_as)
						.setOnMenuItemClickListener(l);
				;
			}
			menu.add(0, MENU_DETAIL, 0, R.string.operate_viewdetails)
					.setOnMenuItemClickListener(l);
		}
	};

	private final class FileListMenuClickListener implements
			MenuItem.OnMenuItemClickListener {
		private File mClickedFile;
		private Uri mClickedFileUri;

		public FileListMenuClickListener(File selectedFile, Uri selectedFileUri) {
			mClickedFile = selectedFile;
			mClickedFileUri = selectedFileUri;
		}

		DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				ActivityUtils.startPasteMode(which);
				finish();
			}
		};

		@Override
		public boolean onMenuItemClick(MenuItem item) {
			if (mClickedFile == null && mClickedFileUri == null) {
				return false;
			}

			switch (item.getItemId()) {
			case MENU_COPY:
				FileUtil.copy(mContext, mClickedFile, false);
				if (StorageUtil.getExternalStorageState().equals("mounted")) {
					ActivityUtils.showDestSelectDialog(mContext, listener);
				} else {
					ActivityUtils.startPasteMode(0);
				}
				return true;
			case MENU_CUT:
				FileUtil.copy(mContext, mClickedFile, true);
				if (StorageUtil.getExternalStorageState().equals("mounted")) {
					ActivityUtils.showDestSelectDialog(mContext, listener);
				} else {
					ActivityUtils.startPasteMode(0);
				}

				return true;
			case MENU_DELETE:
				new AlertDialog.Builder(mContext)
						.setTitle(R.string.operate_delete)
						.setMessage(R.string.confirm_delete)
						.setPositiveButton(android.R.string.ok,
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub
										// TODO Auto-generated method stub
										if (mAdapter instanceof QuickScanCursorAdapter) {
											FileUtil.deleteSingleFile(
													mClickedFile, mContext,
													mHandler);
										}
									}
								})
						.setNegativeButton(android.R.string.cancel, null)
						.show();
				return true;
			case MENU_SHARE:
				Intent intent = new Intent(Intent.ACTION_SEND);
				String type = FileType.getFileType(OverViewActivity.this)
						.getTypeByFile(mClickedFile);
				Uri uri = Uri.parse("file://" + mClickedFile.getPath());
				intent.setType(type);
				intent.putExtra(Intent.EXTRA_STREAM, uri);
				startActivity(Intent.createChooser(intent, mContext
						.getResources().getString(R.string.operate_share)));
				return true;
			case MENU_RENAME:
				if (mAdapter instanceof QuickScanCursorAdapter) {
					FileUtil.rename(mClickedFile, mClickedFileUri,
							(QuickScanCursorAdapter) mAdapter, mContext);
				}

				return true;
			case MENU_DETAIL:
				FileUtil.viewDetails(mClickedFile, mContext);
				return true;
			case MENU_SETAS:
				Intent intent2 = new Intent(Intent.ACTION_ATTACH_DATA)
						.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
				String type2 = FileType.getFileType(OverViewActivity.this)
						.getTypeByFile(mClickedFile);
				Uri uri2 = MediaStore.Files.getContentUri("external");
				Cursor cursor = mContext.getContentResolver().query(uri2,
						new String[] { MediaStore.Files.FileColumns._ID },
						MediaStore.Files.FileColumns.DATA + "=?",
						new String[] { mClickedFile.getPath() }, null);
				cursor.moveToFirst();
				long id = cursor.getLong(0);
				cursor.close();
				intent2.setDataAndType(ContentUris.withAppendedId(uri2, id),
						type2);
				mContext.startActivity(Intent.createChooser(intent2, mContext
						.getResources().getString(R.string.set_as)));
			default:
				return false;
			}
		}

		private Handler mHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case FileUtil.REFREAH_FILELIST:
					if (mAdapter instanceof QuickScanCursorAdapter) {
						((QuickScanCursorAdapter) mAdapter).refresh();
					}
					break;
				default:
					break;
				}
			};
		};
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (menu != null) {
			menu.removeGroup(1);
		}
		switch (this.mFileType) {
		case FileType.FILE_TYPE_IMAGE:
		case FileType.FILE_TYPE_AUDIO:
		case FileType.FILE_TYPE_VIDEO:
		case FileType.FILE_TYPE_DOC:
			menu.add(1, this.MENU_MULTISELECT, 0,
					R.string.overview_menu_multiselect);
			menu.add(1, this.MENU_SORT, 0, R.string.overview_menu_sort);
			break;
		case FileType.FILE_TYPE_PACKAGE:
			menu.add(1, this.MENU_MULTISELECT, 0,
					R.string.overview_menu_multiselect);
			menu.add(1, this.MENU_INSTALL_ALL, 0,
					R.string.overview_menu_install_all);
			menu.add(1, this.MENU_SORT, 0, R.string.overview_menu_sort);
			break;
		}
		if (mAdapter != null && mAdapter.getCount() > 0) {
			menu.setGroupEnabled(1, true);
		} else {
			menu.setGroupEnabled(1, false);
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			return true;
		case MENU_MULTISELECT:
			Intent multiSelectIntent = new Intent(mContext,
					MultiSelectActivity.class);
			multiSelectIntent.putExtra("fileType", mFileType);
			multiSelectIntent.putExtra("position",
					mListView.getFirstVisiblePosition());
			startActivityForResult(multiSelectIntent, MULTI_SELECT);
			break;
		case MENU_SORT:
			AlertDialog.Builder sortTypeDialog = new AlertDialog.Builder(
					mContext);
			sortTypeDialog.setTitle(R.string.menu_sort_type);
			final int sortType;
			final SharedPreferences settings = mContext.getSharedPreferences(
					FileSort.FILE_SORT_KEY, 0);
			sortType = settings.getInt(FileSort.FILE_SORT_KEY,
					FileSort.SORT_BY_NAME);
			int selectItem = FileSort.getFileListSort().getSelectItemByType(
					sortType);
			mSortBy = selectItem;
			sortTypeDialog.setSingleChoiceItems(R.array.sort_type, selectItem,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							mSortBy = whichButton;
						}
					});
			sortTypeDialog.setNegativeButton(R.string.sort_by_asc,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							switch (mSortBy) {
							case 0:
								mSortBy = FileSort.SORT_BY_NAME;
								break;
							case 1:
								mSortBy = FileSort.SORT_BY_TYPE;
								break;
							case 2:
								mSortBy = FileSort.SORT_BY_TIME_ASC;
								break;
							case 3:
								mSortBy = FileSort.SORT_BY_SIZE_ASC;
								break;
							}
							settings.edit()
									.putInt(FileSort.FILE_SORT_KEY, mSortBy)
									.commit();
							FileSort.getFileListSort().setSortType(mSortBy);

							// bug 208580 begin
							new Thread(new Runnable() {
								@Override
								public void run() {
									FileSort.getFileListSort().sort(
											mAdapter.getFileList());
									handler.post(new Runnable() {

										@Override
										public void run() {
											mAdapter.notifyDataSetChanged();
										}
									});
								}
							}).start();
							// bug 208580 end
						}
					});
			sortTypeDialog.setPositiveButton(R.string.sort_by_desc,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							switch (mSortBy) {
							case 0:
								mSortBy = FileSort.SORT_BY_NAME_DESC;
								break;
							case 1:
								mSortBy = FileSort.SORT_BY_TYPE_DESC;
								break;
							case 2:
								mSortBy = FileSort.SORT_BY_TIME_DESC;
								break;
							case 3:
								mSortBy = FileSort.SORT_BY_SIZE_DESC;
								break;
							}
							settings.edit()
									.putInt(FileSort.FILE_SORT_KEY, mSortBy)
									.commit();
							FileSort.getFileListSort().setSortType(mSortBy);

							// bug 208580 begin
							new Thread(new Runnable() {
								@Override
								public void run() {
									FileSort.getFileListSort().sort(
											mAdapter.getFileList());
									handler.post(new Runnable() {
										@Override
										public void run() {
											mAdapter.notifyDataSetChanged();
										}
									});
								}
							}).start();
							// bug 208580 end
						}
					});
			sortTypeDialog.show();
			break;
		case MENU_INSTALL_ALL:
			if (mAdapter instanceof QuickScanCursorAdapter) {
				List<File> apkList = mAdapter.getFileList();
				for (File file : apkList) {
					Intent intent = IntentUtil.getIntentByFileType(mContext,
							mFileType, file);
					if (intent != null) {
						mContext.startActivity(intent);
					} else {
						Toast.makeText(mContext, R.string.msg_invalid_intent,
								Toast.LENGTH_SHORT).show();
					}
				}
			}
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			finish();
			ActivityUtils.startPasteMode(which);
		}
	};

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case MULTI_SELECT: {
			if (data != null) {
				ArrayList<File> selectedFiles = (ArrayList<File>) data
						.getSerializableExtra("selectedFiles");
				int operationType = data.getIntExtra("operation", -1);
				if (operationType == R.id.menu_delete) {
					if (selectedFiles != null) {
						FileUtil.delete(selectedFiles, mContext, mAdapter);
					}
				} else if (operationType == R.id.menu_copy) {
					if (StorageUtil.getExternalStorageState().equals("mounted")) {
						Builder builder = new AlertDialog.Builder(this);
						builder.setTitle(R.string.select_destination);
						BaseAdapter adapter = new CopyDestListAdapter();
						builder.setAdapter(adapter, listener);
						builder.create().show();
					} else {
						finish();
						ActivityUtils.startPasteMode(0);
					}
				}
			}
		}
		}
	}

}
